package com.ljm.security.listener;

import com.ljm.cache.service.ICacheService;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author: ChenHuaMing
 * @Date: 2020/10/15 17:26
 * @Description:
 */
@Configuration
public class AuthenticationFailureListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
    private final String prefix="security:badCredentials:";
    @Resource
    private ICacheService cacheService;

    @Override
    public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent authenticationFailureBadCredentialsEvent) {
        Authentication authentication = authenticationFailureBadCredentialsEvent.getAuthentication();
        String loginName=authentication.getPrincipal().toString();
        UserLockInfo userLockInfo = (UserLockInfo) cacheService.get(prefix + loginName);
        if(userLockInfo==null){
            WebAuthenticationDetails auth = (WebAuthenticationDetails) authenticationFailureBadCredentialsEvent.getAuthentication().getDetails();
            userLockInfo=new UserLockInfo(loginName,1,auth.getRemoteAddress());
        }else{
            userLockInfo.setTimes(userLockInfo.getTimes()+1);
        }
        cacheService.set(prefix + loginName,userLockInfo,30L, TimeUnit.MINUTES);
    }
}
